<?php
namespace Admin\Controller;

class ZoneController extends Controller {

    public function index() {
        $m    = D('Zone');
        $page = $m->where($this->indexExpr)->order($this->sortExpr)->page2();

        $this->assign('page', $page);
        $this->display();
    }

    public function add() {
        $planId = empty($_GET['plan_id']) ? 0 : (int)$_GET['plan_id'];

        if(empty($planId)) {
            throw new ThinkException('没有计划编号，无法增加广告');
        }

        if(!$rPlan = D2('Plan')->getByPlanId($planId)) {
            throw new ThinkException('没有找到计划信息');
        }

        $record = array(
            'plan_id'   => $rPlan['planid'],
            'plan_type' => $rPlan['plantype'],
            'plan_name' => $rPlan['planname'],
            'url'       => $rPlan['url'],
        );

        $this->assign('record', $record);
        $this->display();
    }

    public function detail() {
        $this->modify();
    }

    public function modify() {
        $id = empty($_GET['id']) ? 0 : (int)$_GET['id'];

        if(empty($id)) {
            throw new ThinkException('参数不完整，无法获取数据');
        }

        $m = D2('VZone');

        if(!$record = $m->getByZoneId($id)) {
            throw new ThinkException('没有找到广告位信息');
        }

        $uid   = $record['uid'];
        $limit = array();

        if($tmpLimit = D2('Siter')->getLimit($uid)) {
            $_key  = strtolower($record['plan_type']) . '_limit';
            $limit = empty($tmpLimit[$_key]) ? array() : $tmpLimit[$_key];
        }

        $mAd = D2('Ad');
        $rAd = $mAd->getAdsByTypeAndSize($record['zone_type'], $record['zone_width'], $record['zone_height']);
        $tpl = in_array($record['zone_type'], array('zn_tw', 'zn_text', 'zn_color_cloud')) ? 'modify2' : 'modify';

        $this->assign('limit', $limit);     //被限制投放的计划编号
        $this->assign('ad', $rAd);
        $this->assign('record', $record);
        $this->display($tpl);
    }

    public function doSave() {
        $d = $_POST;
        $m = D2();

        try {
            $r = $m->save2($d) ? array('s' => true, 'm' => '保存成功') : array('s' => false, 'm' => '保存出错');
        } catch (Exception $e) {
            $r = array('s' => false, 'm' => $e->getMessage());
        }

        echo json_encode($r);
    }

    public function del() {
        $id = empty($_GET['id']) ? 0 : (int)$_GET['id'];

        if(empty($id)) {
            showJson(array('s' => false, 'm' => '参数不完整，无法删除数据'));
        }

        $m = D2();

        try {
            $r = $m->del($id) ? array('s' => true, 'm' => '删除成功') : array('s' => false, 'm' => '删除出错');
        } catch(Exception $e) {
            $r = array('s' => false, 'm' => $e->getMessage());
        }

        showJson($r);
    }

    /**
     * preview
     * 智能广告位预览
     *
     * @return void
     */
    public function preview() {
        $type   = empty($_GET['zone_type'])   ? '' : $_GET['zone_type'];
        $width  = empty($_GET['zone_width'])  ? 0  : (int)$_GET['zone_width'];
        $height = empty($_GET['zone_height']) ? 0  : (int)$_GET['zone_height'];

        if(empty($type) || empty($width) || empty($height)) {
            exit('参数不完整');
        }

        $m     = D2('Zone');
        $error = '';

        try {
            if(!$adInfo = $m->getZnAdInfo($type, $width, $height)) {
                $error = '没有找到合适的广告';
            }
        } catch(Exception $e) {
            $error = $e->getMessage();
        }

        if(!empty($error)) {
            exit($error);
        }

        $total    = $adInfo['col'] * $adInfo['row'];
        $cssClass = "size-{$width}x{$height}";
        $html = <<<EOD
<style type="text/css">
.{$cssClass} { width:{$width}px; height:{$height}px; overflow:hidden; }
</style>
EOD;

        $html .= '<ul class="ad-box ' . $cssClass . ' ' . $ad['list-style'] . '">';

        for($i = 0; $i < $total; $i++) {
            $html .= '<li>' . $adInfo['html'] . '</li>';
        }

        $html .= '</ul>';

        $this->assign('html', $html)->display();
    }

    /**
     * doZnZoneSave
     * 保存智能广告位
     *
     * @return void
     */
    public function doZnZoneSave() {
        $d      = $_POST;
        $m      = D2('Zone');
        $action = strtolower($d['zone_type']) == 'zn_color_cloud' ? 'saveZnColorCloud' : 'saveZnZone';

        try {
            //saveZnZone()成功时返回广告位编号，出错时返回false
            $r = (!$_r = $m->$action($d)) ?  array('s' => false, 'm' => '保存广告位出错') : array('s' => true, 'd' => $_r);
        } catch(Exception $e) {
            $r = array('s' => false, 'm' => $e->getMessage());
        }

        showJson($r);
    }

    /**
     * checkHasAd
     * 检测广告位是否有对应广告
     *
     * @return void
     */
    public function checkHasAd() {
        $m = D2();
        $r = array();

        if(!$records = $m->order('zone_id ASC')->select()) {
            exit('NOT FOUND ZONE');
        }

        $mUser = D2('User');
        $mAd   = M('v_ad');

        foreach($records as $v) {
            if(!$_user = $mUser->where(array('uid' => $v['uid']))->find()) {
                continue;
            }

            if($_user['status'] != 2) {
                continue;
            }

            $_adExpr = array(
                'type'   => $v['zone_type'],
                'width'  => $v['zone_width'],
                'height' => $v['zone_height'],
            );

            if(!$_ads = $mAd->where($_adExpr)->select()) {
                $r[] = $v;

                continue;
            }

            $isAllNotActive = 1;

            foreach($_ads as $_ad) {
                if($_ad['status'] == 1 && $_ad['plan_status'] == 1) {
                    $isAllNotActive = 0;

                    break;
                }
            }

            if($isAllNotActive) {
                $r[] = $v;
            }
        }

        $this->assign('record', $r);
        $this->display();
    }

}
